<template>
  <div class="search">
    <van-search
      v-model="value"
      placeholder="请输入商品名称"
      shape="round"
      show-action
      ref="search"
      @input="searchProductData"
      class="s"
    >
      <template #action>
        <div @click="hiddenOverlay">取消</div>
      </template>
    </van-search>
    <div class="searchProduct">
      <ul v-if="typeProductData[0] != undefined">
        <li v-for="(item, index) in typeProductData" :key="index">
          <Product :data="item" />
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Product from "../components/Product.vue";

export default {
  name: "Search",

  components: {
    Product,
  },

  props: {
    show: Boolean,
  },

  data() {
    return {
      value: "",
      typeProductData: [],
      timer: null
    };
  },

  created() {
    // 获取焦点
    this.changfouce();
  },

  watch: {
    // 监听搜索状态变化执行获取焦点函数
    show() {
      this.changfouce();
    },
  },

  methods: {
    hiddenOverlay() {
      this.$emit("hiddenOverlay");
    },

    // 获取焦点
    changfouce() {
      this.$nextTick(() => {
        this.$refs.search.querySelectorAll("input")[0].focus();
      });
    },

    // 搜索商品
    searchProductData(key) {
      // 防抖
      if(this.timer) clearTimeout(this.timer);
      // 输入框为空不进行请求
      if(!key) {
        this.typeProductData = [];
        return;
      }
      this.timer = setTimeout(() => {
        // 请求数据
        this.axios({
          method: "get",
          url: "/search",
          params: {
            name: key,
          },
        })
          .then((res) => {
            this.typeProductData = res.data.result;
          })
          .catch((err) => {});
      }, 500);
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  padding-top: 28px;
  height: 100%;
  background: #fff;
    overflow-y: auto;
  ul {
    display: grid;
    grid-template-columns: repeat(3, calc(33.33333% - 12px));
    justify-content: space-evenly;
    margin-top: 54px;
    padding: 10px 0;
    // grid-template-columns: repeat(3, 33.33333%);
    gap: 10px 0;
    text-align: center;
  }
  .s {
    position: fixed;
    width: 100%;
  }
}
</style>